package com.kim.rssreader.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

import com.kim.rssreader.domain.constant.CityWeatherCode;
import com.kim.rssreader.domain.constant.RssCategoryConstant;
import com.kim.rssreader.domain.constant.RssColumnConstant;
import com.kim.rssreader.domain.constant.RssContentConstant;
import com.kim.rssreader.domain.constant.RssImageConstant;
import com.kim.rssreader.domain.constant.SubscriptionContant;

public class BaseDBHelper extends SQLiteOpenHelper {
	private Context ctx;

	public BaseDBHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		ctx = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		createTable(db);
		DataFactory.generateBuildinCategoryData(db);
		DataFactory.generateBuildinColumnData(db);
		generateMoreDataDefault(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if (newVersion > 1) {
			createTableMoreOne2Two(db);
			updateTableOne2two(db);
			generateMoreDataDefault(db);
		}
		if (newVersion > 2) {
			two2three(db);
		}
	}

	private void createTable(SQLiteDatabase database) {
		database.execSQL(RssCategoryConstant.SQL_CREATE);
		database.execSQL(RssColumnConstant.SQL_CREATE);
		database.execSQL(RssContentConstant.SQL_CREATE);
		createTableMoreOne2Two(database);
	}

	private void createTableMoreOne2Two(SQLiteDatabase db) {
		// 增加内容区图片地址表
		db.execSQL(RssImageConstant.SQL_CREATE);
		db.execSQL(SubscriptionContant.SQL_CREATE);
		db.execSQL(CityWeatherCode.SQL_CREATE);
	}

	private void generateMoreDataDefault(SQLiteDatabase db) {
		//新增内置rss
		DataFactory.generateMoreRssColumnInfo(db);
		//天气城市代码
		DataFactory.generateCityWeatherCode(db, ctx);
		//默认订阅rss
		DataFactory.generateDefaultSubscription(db);
	}
	private void updateTableOne2two(SQLiteDatabase db) {
		// 内容表增加是否已读标记
		db.execSQL("ALTER TABLE " + RssContentConstant.TABLE_NAME
				+ " ADD COLUMN " + RssContentConstant.CONTENTREAD + " bit");
	}

	private void two2three(SQLiteDatabase db) {

	}

}
